import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Form, Input, Button, Toast } from 'antd-mobile'
import Nabar from '../../conpoment/Nabar'
import http from '../../api/index'
import styles from './index.module.css'

interface ProfileData {
  name: string
  standing: string
  birthday: string
  sex: string
  phone: string
  relation: string
  age: string
}

function Index() {
  const navigate = useNavigate()
  const [form] = Form.useForm()
  const [selectedRelationship, setSelectedRelationship] = useState('本人')
  const [selectedGender, setSelectedGender] = useState('')

  const relationships = [
    { key: '本人', label: '本人' },
    { key: '配偶', label: '配偶' },
    { key: '父母', label: '父母' },
    { key: '子女', label: '子女' },
    { key: '亲戚', label: '亲戚' },
    { key: '朋友', label: '朋友' },
    { key: '其他', label: '其他' }
  ]

  const handleRelationshipSelect = (relationship: string) => {
    setSelectedRelationship(relationship)
    form.setFieldsValue({ relation: relationship })
  }

  const handleGenderSelect = (gender: string) => {
    setSelectedGender(gender)
    form.setFieldsValue({ sex: gender })
  }

  const onFinish = async (values: ProfileData) => {
    try {
      console.log('保存档案数据:', values)

      // 计算年龄
      const calculateAge = (birthday: string) => {
        try {
          // 处理不同格式的生日输入
          let birthDate: Date

          // 如果是8位数字格式 (YYYYMMDD)
          if (/^\d{8}$/.test(birthday)) {
            const year = parseInt(birthday.substring(0, 4))
            const month = parseInt(birthday.substring(4, 6)) - 1 // 月份从0开始
            const day = parseInt(birthday.substring(6, 8))
            birthDate = new Date(year, month, day)
          } else {
            // 尝试直接解析
            birthDate = new Date(birthday)
          }

          // 检查日期是否有效
          if (isNaN(birthDate.getTime())) {
            console.error('无效的生日格式:', birthday)
            return '0'
          }
          // 计算年龄的函数
          const today = new Date()
          let age = today.getFullYear() - birthDate.getFullYear()
          const monthDiff = today.getMonth() - birthDate.getMonth()
          if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
            age--
          }
          return age.toString()
        } catch (error) {
          console.error('计算年龄时出错:', error)
          return '0'
        }
      }

      // 准备API请求数据
      const apiData = {
        name: values.name,
        standing: values.standing,
        birthday: values.birthday,
        sex: selectedGender, // 使用状态值而不是表单值
        phone: values.phone,
        relation: selectedRelationship, // 使用状态值而不是表单值
        age: calculateAge(values.birthday)
      }

      console.log('表单数据:', values)
      console.log('选中的性别:', selectedGender)
      console.log('选中的关系:', selectedRelationship)
      console.log('API请求数据:', apiData)

      // 调用API接口
      const response = await http.put('/api/user/list', apiData)

      if (response.data) {
        Toast.show({
          content: '档案保存成功！',
          icon: 'success'
        })

        // 设置sessionStorage记录路由来源
        sessionStorage.setItem('lastRoute', '/create')

        // 将保存的数据通过路由参数传递
        navigate('/wenz', {
          state: {
            savedProfile: apiData,
            fromCreate: true
          }
        })
      }
    } catch (error) {
      console.error('保存档案失败:', error)
      Toast.show({
        content: '保存失败，请重试',
        icon: 'fail'
      })
    }
  }
  return (
    <div className={styles.container}>
      <Nabar title='新建档案' sticky={false} />

      <div className={styles.content}>
        {/* 重要提示 */}
        <div className={styles.notice}>
          根据国家有关规定,就诊人在未实名认证状态下,平台将无法提供诊断、药品、挂号等服务,请及时实名认证!
        </div>

        {/* 基本信息标签 */}
        <div className={styles.sectionTab}>
          基本信息
        </div>
      </div>
      {/* 表单 */}
      <Form
        form={form}
        onFinish={onFinish}
        layout="horizontal"
        className={styles.form}
      >
        {/* 与您的关系 */}
        <div className={styles.formSection}>
          <div className={styles.label}>
            <span className={styles.required}>*</span>
            与您的关系:
          </div>
          <div className={styles.relationshipOptions}>
            {relationships.map((rel) => (
              <button
                key={rel.key}
                type="button"
                className={`${styles.relationshipOption} ${selectedRelationship === rel.key ? styles.selected : ''
                  }`}
                onClick={() => handleRelationshipSelect(rel.key)}
              >
                {rel.label}
              </button>
            ))}
          </div>
        </div>

        {/* 姓名 */}
        <Form.Item
          name="name"
          label={
            <span className={styles.label}>
              <span className={styles.required}>*</span>
              姓名:
            </span>
          }
          rules={[{ required: true, message: '请输入真实姓名' }]}
        >
          <Input placeholder="请输入真实姓名" className={styles.input} />
        </Form.Item>

        {/* 身份证 */}
        <Form.Item
          name="standing"
          label={
            <span className={styles.label}>
              <span className={styles.required}>*</span>
              身份证:
            </span>
          }
          rules={[
            { required: true, message: '请输入身份证号码' },
            { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '身份证格式不正确' }
          ]}
        >
          <Input placeholder="请输入身份证号码" className={styles.input} />
        </Form.Item>

        {/* 出生日期 */}
        <Form.Item
          name="birthday"
          label={
            <span className={styles.label}>
              <span className={styles.required}>*</span>
              出生日期:
            </span>
          }
          rules={[{ required: true, message: '请选择出生日期' }]}
        >
          <Input placeholder="请输入出生日期" className={styles.input} />
        </Form.Item>

        {/* 性别 */}
        <div className={styles.formSection}>
          <div className={styles.label}>
            <span className={styles.required}>*</span>
            性别:
          </div>
          <div className={styles.genderOptions}>
            <button
              type="button"
              className={`${styles.genderOption} ${selectedGender === '男' ? styles.selected : ''
                }`}
              onClick={() => handleGenderSelect('男')}
            >
              ♂ 男
            </button>
            <button
              type="button"
              className={`${styles.genderOption} ${selectedGender === '女' ? styles.selected : ''
                }`}
              onClick={() => handleGenderSelect('女')}
            >
              ♀ 女
            </button>
          </div>
        </div>

        {/* 联系方式 */}
        <Form.Item
          name="phone"
          label={
            <span className={styles.label}>
              <span className={styles.required}>*</span>
              联系方式:
            </span>
          }
          rules={[
            { required: true, message: '请输入手机号码' },
            { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
          ]}
        >
          <Input placeholder="请输入手机号码" className={styles.input} />
        </Form.Item>

        {/* 保存按钮 */}
        <Button
          type="submit"
          className={styles.saveButton}
          block
        >
          保存
        </Button>
      </Form>
    </div>
  )
}

export default Index
